package com.servlet;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.dao.CurriInfoDao;
import com.dao.PaperInfoDao;
import com.model.PaperInfo;
import com.util.ModelPaperInfo;

/**
 * Servlet implementation class ClassServlet
 */
@WebServlet("/PaperInfoServlet")
public class PaperInfoServlet extends HttpServlet {
	PaperInfoDao pid=new PaperInfoDao();
	CurriInfoDao cid=new CurriInfoDao();
	/**
	 * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		String op=request.getParameter("op");
		
		
		
		if("add".equals(op)) {
			String name=request.getParameter("paname");
			int pd=0;
			PaperInfo p=new PaperInfo();
			p.setCurId(Integer.parseInt(request.getParameter("pacuname")));
			p.setPaperName(name);
			Date d=new Date();
			SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String time=sdf.format(d).toString();
			p.setCreateTime(time);
			if(pid.selectByname(name)==1) {
				pd=pid.insertAll(name,"修改",p);
			}else {
				pd=pid.insertAll(name,"添加",p);
			}
			
			if(pd==1) {
				response.getWriter().print("添加成功");
			}else{
				response.getWriter().print("添加失败,该试卷可能已存在,");
			}
		}else if("update".equals(op)){
			PaperInfo c=new PaperInfo();
			c.setPaperId(Integer.parseInt(request.getParameter("paperid")));
			c.setCurId(cid.selectIdByName(request.getParameter("curname")));
			c.setPaperName(request.getParameter("papername"));
			if(pid.updateById(c)==1) {
				response.getWriter().print("修改成功");
			}else{
				response.getWriter().print("修改失败");
			}
		}else if("delete".equals(op)){
			if(pid.deleteById(Integer.parseInt(request.getParameter("id")))==1) {
				response.getWriter().print("删除成功");
			}else{
				response.getWriter().print("删除失败");
			}
		}else if("select".equals(op)){
			String rows=request.getParameter("rows");
			String page=request.getParameter("page");
			String name=request.getParameter("name");
			int km=0;
			if(request.getParameter("km")!=null) {
				km=Integer.parseInt(request.getParameter("km"));
			}
			
			ModelPaperInfo list=pid.selectAll(Integer.parseInt(page), Integer.parseInt(rows), name,km);
			response.getWriter().print(JSON.toJSONString(list));
		}
		
	}

}
